﻿using System;
using UnityEngine;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.IO;
using System.Collections;

/// <summary>
/// Json数据管理器
/// </summary>
public class DataManager : MonoSingleton<DataManager>
{
    public Dictionary<int, RoleData> RoleInfo = null;

    //public Dictionary<string, Sprite> spriteItems = new Dictionary<string, Sprite>();

    /// <summary>
    /// 加载配置文件
    /// </summary>
    public void Load()
    {
        StartCoroutine(LoadData());
    }

    IEnumerator LoadData()
    {
        Debug.Log("配置表 === 加载中...");
        yield return RoleInfo = Json2Info<int, RoleData>("./Data/RoleConfig.txt");
        Debug.Log("配置表 === 加载完成");
        foreach (var item in RoleInfo)
        {
            Debug.Log($"{item.Value.name}|{item.Value.attack}|{item.Value.attack_rate}|{item.Value.hp}");
        }
        //图片资源加载
        //spriteItems.Add("Card/bg_bg_normal", Instantiate(Resources.Load("Card/bg_bg_normal", typeof(Sprite))) as Sprite);
        //spriteItems.Add("Card/bg_bg_skill", Instantiate(Resources.Load("Card/bg_bg_skill", typeof(Sprite))) as Sprite);
        //spriteItems.Add("Card/bg_bg_prop", Instantiate(Resources.Load("Card/bg_bg_prop", typeof(Sprite))) as Sprite);
        //foreach (var item in cardItems)
        //{
        //    if (item.Value.Type == ItemType.NORMAL)
        //    {
        //        continue;
        //    }
        //    spriteItems.Add(item.Value.Icon, Instantiate(Resources.Load(item.Value.Icon, typeof(Sprite)) as Sprite));
        //}
        yield return null;
        //Debug.Log("图片资源- 加载完成");
    }

    Dictionary<TKey, TValue> Json2Info<TKey, TValue>(string path)
    {
        Console.WriteLine($"[JsonData]:{path}");
        string json = File.ReadAllText(path);
        return JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(json);
    }

    //获取数据的同时，校验
    public T GetData<T>(Dictionary<int, T> info, int id)
    {
        if (info.ContainsKey(id))
        {
            return info[id];
        }
        Debug.Log($"不存在的ID -> {default(T).ToString()}");
        return default(T);
    }

}
